<template>
	<a-modal v-bind="optionDialog">
		<div v-if="isConfirmedFinish">房间物业交割单已全部确认，操作保存即可查看。</div>
		<div v-else>房间物业交割单批量查询确认中，若操作取消，已确认房间的数据将不会保存，请耐心等候!</div>
		<a-row v-for="(item, index) in unconfirmedList" :key="index" :gutter="[0, 1]">
			<a-space v-if="1 === item.confirmStatus" :size="10">
				<a>{{ item.houseAddress }} 已确认</a>
				<check-outlined v-color="{color: 'green'}" />
			</a-space>
			<a-space v-else-if="0 === item.confirmStatus" :size="10">
				<a>{{ item.houseAddress }} 确认中</a>
				<loading-outlined v-color="{color: 'green'}" />
			</a-space>
			<a-space v-else :size="10">
				<a>{{ item.houseAddress }} 确认失败</a>
				<close-outlined v-color="{color: 'error'}" />
			</a-space>
		</a-row>
		<template #footer>
			<a-button @click.stop="optionDialog.onCancel">取消</a-button>
			<a-button type="primary" v-if="isConfirmedFinish" @click="submit">确定</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {ref, reactive, toRef, watch, computed} from 'vue'
	import XEUtils from 'xe-utils'
	import {LoadingOutlined, CheckOutlined, CloseOutlined} from '@ant-design/icons-vue'
	import {defaultMeters} from '@/interface/contract'
	import {getCurEleAndWaterQuantity, getHouseDeliveryGetNoe, houseConfigGetList} from '@/api/contract'
	import {isLockinEnv} from 'yuxin-base/src/utils'

	const props = defineProps<{
		visible: boolean
		enterPriseContracList: Array<any>
	}>()
	const emits = defineEmits(['update:visible', 'close'])
	const optionDialog = reactive({
		width: 500,
		title: '物业交割单批量确认',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		class: 'batch-delivery-dialog',
		visible: toRef(props, 'visible'),
		bodyStyle: {
			paddingTop: '10px',
			paddingBottom: '10px',
			maxHeight: '500px',
			overflowY: 'auto'
		},
		onCancel() {
			emits('update:visible', false)
		}
	})

	// 未确认的房间
	const unconfirmedList = ref<Array<any>>([])

	// 是否确认结束
	const isConfirmedFinish = computed(() => {
		return !unconfirmedList.value.filter(i => 0 === i.confirmStatus).length
	})

	const setRowStatus = (row, type) => {
		const mapConfirmStatus = {
			0: '确认中',
			1: ' - 已确认',
			2: ' - 未确认'
		}
		if (1 === type) {
			// 确认成功
			row.isSure = true
			row.disabled = !row.isSure
			row.confirmStatus = 1
			row.address = row.houseAddress + `${mapConfirmStatus[row.confirmStatus]}`
		} else {
			// 确认失败
			row.isSure = false
			row.disabled = !row.isSure
			row.confirmStatus = 2
			row.address = row.houseAddress + `${mapConfirmStatus[row.confirmStatus]}`
		}
	}

	// 通过合同id获取物业交割单详情
	const getDeliveryGetNoe = async (houseId: string, row: any): Promise<any> => {
		const params = {
			id: houseId,
			type: 1
		}
		const modelRef = {
			comment: null,
			attachments: JSON.stringify([]),
			articles: [],
			transferWhArticles: [],
			meters: defaultMeters(),
			attachmentDtos: []
		}
		// 获取资产
		const getArticles = await houseConfigGetList(houseId)
		return new Promise<any>((resolve, reject) => {
			// 获取房间信息
			getHouseDeliveryGetNoe(params)
				.then((res: any) => {
					if (res.data) {
						modelRef.articles = res.data?.articles || getArticles?.data?.articles || []
						modelRef.attachmentDtos = res.data?.attachmentDtos || []
						modelRef.comment = res.data?.comment || ''
						modelRef.attachments = JSON.parse(res.data?.attachments) || ''
					}
					setRowStatus(row, 1)
				})
				.finally(() => {
					if (isLockinEnv()) {
						setEleAndWaterQuantity(houseId)
							.then(baseNumbe => {
								if (baseNumbe.clodWaterMaterStatusName == '在线') {
									modelRef.meters[0].read = baseNumbe.coldWaterMaterRead
								}
								if (baseNumbe.eleMaterStatusName == '在线') {
									modelRef.meters[3].read = baseNumbe.eleMaterRead
								}
								if (baseNumbe.hotWaterMaterStatusName == '在线') {
									modelRef.meters[2].read = baseNumbe.hotWaterMaterRead
								}
								if (
									[
										baseNumbe.eleMaterStatusName,
										baseNumbe.clodWaterMaterStatusName,
										baseNumbe.hotWaterMaterStatusName
									].includes('离线')
								) {
									setRowStatus(row, 2)
								}
							})
							.catch(() => {
								// 获取失败和离线都算作确认失败
								setRowStatus(row, 2)
							})
							.finally(() => {
								resolve(modelRef)
							})
					} else {
						resolve(modelRef)
					}
				})
		})
	}

	// 获取水电表读数
	const setEleAndWaterQuantity = (houseId: string) => {
		return new Promise<any>((resolve, reject) => {
			getCurEleAndWaterQuantity({
				roomId: houseId
			})
				.then((res: any) => {
					const baseNumbe = res.data
					resolve(baseNumbe)
				})
				.catch(err => {
					reject(err)
				})
		})
	}

	// 确认物业交割单
	const confirmDelivery = async (enterPriseContractRow: any) => {
		const e = enterPriseContractRow
		let modelRef = {
			comment: null,
			attachments: [],
			articles: [],
			transferWhArticles: [],
			meters: defaultMeters(),
			attachmentDtos: []
		}

		const {houseId} = e
		return new Promise<any>((resolve, reject) => {
			getDeliveryGetNoe(houseId, e)
				.then(newModelRef => {
					modelRef = newModelRef
					e.deliveryAddForm = {
						...modelRef,
						contractType: 2, // 合同类型-1 个人 2 企业 3 业主
						deliveryType: 1
					}
				})
				.finally(() => {
					resolve(e)
				})
		})
	}

	// 重置
	const resetData = () => {
		unconfirmedList.value = []
	}

	// 提交
	const submit = () => {
		optionDialog.onCancel()
		emits('close', XEUtils.clone(unconfirmedList.value, true))
	}

	// 队列形式 不一次性请求
	const queueReq = (list: Array<any>) => {
		let index = 0
		const max = list.length
		let confirm: any = (row: any) => {
			confirmDelivery(row).then(() => {
				index++
				if (index < max) {
					confirm(list[index])
				} else {
					confirm = null
					return
				}
			})
		}
		confirm(list[index])
	}

	// 定义状态confirmStatus(0 未确认 1 确认成功 2 确认失败)
	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				resetData()
				const enterPriseContracList = XEUtils.clone(props.enterPriseContracList, true)
				unconfirmedList.value = enterPriseContracList.filter(i => !i.isSure).map(i => ({...i, confirmStatus: 0}))
				// 对未确认的物业交割单进行确认
				queueReq(unconfirmedList.value)
			}
		}
	)
</script>

<style lang="less" scoped></style>
